package com.situ.mall.service.impl;

import com.situ.mall.config.RedisConstant;
import com.situ.mall.mapper.ProductMapper;
import com.situ.mall.pojo.Product;
import com.situ.mall.pojo.query.ProductQuery;
import com.situ.mall.service.IProductService;
import com.situ.mall.util.JSONResult;
import com.situ.mall.util.LayUITableJSONResult;
import com.situ.mall.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

// IProductService productService = new ProductServiceImpl()
@Service
public class ProductServiceImpl implements IProductService {

    // IProductDao productDao
    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public LayUITableJSONResult selectByPage(ProductQuery productQuery) {
        int offset = (productQuery.getPage() - 1) * productQuery.getLimit();
        //查询当前页的数据
        List<Product> list = productMapper.selectByPage(offset, productQuery.getLimit(), productQuery);
        //查询总的数量
        int totalCount = productMapper.selectTotalCount(productQuery);

        return LayUITableJSONResult.ok(totalCount, list);
    }

    @Override
    public JSONResult deleteById(Integer id) {
        int count = productMapper.deleteByPrimaryKey(id);
        return count == 1 ? JSONResult.ok("删除成功") : JSONResult.error("删除失败");
    }

    @Override
    public JSONResult deleteAll(Integer[] ids) {
        // delete from product where id in(2, 3)
        int count = productMapper.deleteAll(ids);
        return count == ids.length ? JSONResult.ok("删除成功") : JSONResult.error("删除失败");
    }

    @Override
    public JSONResult add(Product product) {
        int count = productMapper.insert(product);

        // 将上传的图片保存到Redis中
        redisTemplate.opsForSet().add(RedisConstant.UPLOAD_IMAGE_TO_DB, product.getMainImage());
        System.out.println("上传图片到数据库：" + product.getMainImage());

        return count == 1 ? JSONResult.ok("添加成功") : JSONResult.error("添加失败");
    }

    @Override
    public Product selectById(Integer id) {
        return productMapper.selectByPrimaryKey(id);
    }

    @Override
    public JSONResult update(Product product) {
        int count = productMapper.updateByPrimaryKey(product);
        return count == 1 ? JSONResult.ok("修改成功") : JSONResult.error("修改失败");
    }

}
